import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ArenaRecord } from './ArenaRecord';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**竞技场历史记录属性枚举*/
export const enum E_ArenaClientHistory {
	/**找不到的记录id*/
	NOT_FOUND = 0,
	/**无权限的记录id*/
	NOT_ACCESS = 1,
	/**记录<战斗id,>*/
	RECORD = 2,
	/**枚举数量*/
	EnumCount = 3
}


/**竞技场历史记录*/
export class ArenaClientHistory {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ARENA_CLIENT_HISTORY_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ARENA_CLIENT_HISTORY_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ArenaClientHistory[] = [];

	/**创建入口*/
	public static create(json?: string): ArenaClientHistory {
		const c = this.POOL.pop() || new ArenaClientHistory();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**找不到的记录id (long)*/
	protected _notFound: number[] = [];
	/**无权限的记录id (long)*/
	protected _notAccess: number[] = [];
	/**记录<战斗id,>*/
	protected _record: HashMap<number, ArenaRecord> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ArenaClientHistory.POOL.indexOf(this) === -1) {
			ArenaClientHistory.POOL.push(this);
		}
	}

	/**增加找不到的记录id*/
	public addNotFound(v: number): void {
		if (this._notFound.indexOf(v) === -1) {
			this._notFound.push(v);
		}
	}

	/**删除找不到的记录id*/
	public removeNotFound(v: number): void {
		const idx = this._notFound.indexOf(v);
		if (idx >= 0) {
			this._notFound.splice(idx, 1);
		}
	}

	/**获取找不到的记录id列表*/
	public getNotFoundList(): number[] {
		return this._notFound;
	}

	/**增加无权限的记录id*/
	public addNotAccess(v: number): void {
		if (this._notAccess.indexOf(v) === -1) {
			this._notAccess.push(v);
		}
	}

	/**删除无权限的记录id*/
	public removeNotAccess(v: number): void {
		const idx = this._notAccess.indexOf(v);
		if (idx >= 0) {
			this._notAccess.splice(idx, 1);
		}
	}

	/**获取无权限的记录id列表*/
	public getNotAccessList(): number[] {
		return this._notAccess;
	}

	/**设置记录<战斗id,>*/
	public putRecord(k: number, v: ArenaRecord): ArenaRecord {
		const ov = this._record.put(k, v);
		return ov;
	}


	/**获取记录<战斗id,>*/
	public getRecord(k: number) {
		return this._record.get(k);
	}


	/**删除记录<战斗id,>*/
	public removeRecord(k: number, autoDestroy = false): ArenaRecord {
		const ov = this._record.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取记录<战斗id,>映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getRecordKeys(): number[] {
		return this._record.getKeys();
	}


	/**获取记录<战斗id,>映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getRecordValues(): ArenaRecord[] {
		return this._record.getValues();
	}


	/**清空记录<战斗id,>映射表*/
	public clearRecordMap(autoDestroy = false): void {
		const ks = this._record.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeRecord(ks[i], autoDestroy);
		}
	}



	/**通过枚举获取值*/
	public getV(k: E_ArenaClientHistory): any {
		switch (k) {
			case E_ArenaClientHistory.NOT_FOUND: return this._notFound;
			case E_ArenaClientHistory.NOT_ACCESS: return this._notAccess;
			case E_ArenaClientHistory.RECORD: return this._record;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ArenaClientHistory, v: any): void {
		switch (k) {
			case E_ArenaClientHistory.NOT_FOUND: this._notFound = v; break;
			case E_ArenaClientHistory.NOT_ACCESS: this._notAccess = v; break;
			case E_ArenaClientHistory.RECORD: this._record = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//找不到的记录id
		if (this._notFound) {
			this._notFound.length = 0;
		}
		else {
			this._notFound = [];
		}
		//无权限的记录id
		if (this._notAccess) {
			this._notAccess.length = 0;
		}
		else {
			this._notAccess = [];
		}
		//记录<战斗id,>
		if (this._record) {
			const list = this._record.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._record.clear();
		}
		else {
			this._record = new HashMap<number, ArenaRecord>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._notFound) {
			json.notFound = this._notFound;
		}
		if (this._notAccess) {
			json.notAccess = this._notAccess;
		}
		if (this._record.size() > 0) {
			const ks = this._record.getKeys();
			const vs = this._record.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.record = [ks, list];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.notFound) {
			this._notFound = json.notFound;
		}
		if (json.notAccess) {
			this._notAccess = json.notAccess;
		}
		if (json.record) {
			const ks: number[] = json.record[0] || (json.record.getKeys ? json.record.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.record[1] || (json.record.getValues ? json.record.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._record.put(ks[i], ArenaRecord.create(vs[i]));
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//找不到的记录id
		{
			const list = this._notFound;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					byte.writeLongNumber(list[i]);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
		//无权限的记录id
		{
			const list = this._notAccess;
			if (list) {
				byte.writeUint32(list.length);
				for (let i = 0, len = list.length; i < len; i++) {
					byte.writeLongNumber(list[i]);
				}
			}
			else {
				byte.writeUint32(0);
			}
		}
		//记录<战斗id,>
		{
			const ks = this._record.getKeys();
			const vs = this._record.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeLongNumber(ks[i]);
				vs[i].toBytes(byte);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//找不到的记录id
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				this._notFound[i] = byte.readLongNumber();
			}
		}
		//无权限的记录id
		{
			const len = byte.readUint32();
			for (let i = 0; i < len; i++) {
				this._notAccess[i] = byte.readLongNumber();
			}
		}
		//记录<战斗id,>
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readLongNumber();
				const v = ArenaRecord.create();
				v.fromBytes(byte);
				this._record.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): ArenaClientHistory {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ArenaClientHistory.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ArenaClientHistory.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//找不到的记录id
			if (idx === E_ArenaClientHistory.NOT_FOUND) {
				const c: number = us[i + 1];
				const v: number = us[i + 2];
				if (c === 0) {
					const idx = this._notFound.indexOf(v);
					if (idx >= 0) {
						this._notFound.splice(idx, 1);
					}
				}
				else {
					const idx = this._notFound.indexOf(v);
					if (idx === -1) {
						this._notFound.push(v);
					}
				}
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}
			//无权限的记录id
			if (idx === E_ArenaClientHistory.NOT_ACCESS) {
				const c: number = us[i + 1];
				const v: number = us[i + 2];
				if (c === 0) {
					const idx = this._notAccess.indexOf(v);
					if (idx >= 0) {
						this._notAccess.splice(idx, 1);
					}
				}
				else {
					const idx = this._notAccess.indexOf(v);
					if (idx === -1) {
						this._notAccess.push(v);
					}
				}
				IAsync.dispatch(eventID, idx, c, v);
				i += 3;
				continue;
			}

			//记录<战斗id,>
			if (idx === E_ArenaClientHistory.RECORD) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeRecord(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = ArenaRecord.create(us[i + 3]);
					const oldv = this.putRecord(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getRecord(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('ArenaClientHistory ArenaRecord is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			console.error('[Struct Data] can not find enum in ArenaClientHistory with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ArenaClientHistory): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//找不到的记录id
		{
			const idx = E_ArenaClientHistory.NOT_FOUND;
			const rs = MathUtils.intersectSortedArray(this._notFound, other._notFound);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv);
				}
			}
		}

		//无权限的记录id
		{
			const idx = E_ArenaClientHistory.NOT_ACCESS;
			const rs = MathUtils.intersectSortedArray(this._notAccess, other._notAccess);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const newv = list[i];
					updates.push(idx, 1, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					const oldv = list[i];
					updates.push(idx, 0, oldv);
				}
			}
		}

		//记录<战斗id,>
		{
			const idx = E_ArenaClientHistory.RECORD;
			const ks1 = this._record.getKeys();
			const ks2 = other._record.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getRecord(k);
					const oldv = other.getRecord(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getRecord(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ArenaClientHistory.TOTAL_EVENT_ID, this.getV(0));
	}

}
